/**
 *
 * @param {传入文件} file
 * @param {分片后没片的大小默认是1M 传入的单位是按m计算的 类型Number} size
 * @returns {
 *      file//原来的文件
 *      fileName: "",文件原名字
 *      flieChunks: [] //分片之后的数组
 * }
 */
export function fileChunks(file, size = 1) {
  if (!file) {
    throw new Error("文件传入错误");
  }
  var chunkSzie = size * 1024 * 1024;
  var fileLength = file.size;
  var data = {
    file: file,
    fileName: file.name,
    countChunk: Math.ceil(fileLength / chunkSzie),
    flieChunks: [],
  };
  var chunk = 0; //计算出当前分到了多大的长度
  var index = 0; //索引放入
  while (chunk < fileLength) {
    var start = chunk;
    var end = chunk + chunkSzie;
    if (end > fileLength) {
      end = fileLength;
    }
    data.flieChunks.push({
      index: index,
      fileChunk: file.slice(start, end),
    });
    index++;
    chunk += chunkSzie;
  }
  return data;
}
/**
 *
 * @param {传入分片文件的数组} chunks
 * @param {获取分片进度的回调} progressCallback
 * @returns {Promise}
 */
export function fileValidationMD5(chunks, progressCallback) {
  return new Promise((resolve, reject) => {
    var worker = new Worker("/worker/fileMD5.js");
    worker.postMessage({ chunks });
    worker.onmessage = (e) => {
      const { progress, hash } = e.data;
      if (progressCallback && progress) {
        progressCallback(progress.toFixed(2));
      }
      if (hash) {
        resolve(hash);
      }
    };
    worker.onerror = (err) => {
      reject(err);
    };
  });
}
